package com.qboot.monitor.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.qboot.common.entity.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Redis 监控
 *
 * @author Tellsea
 * @date 2023/2/1
 */
@Api(tags = "服务信息 控制层")
@RestController
@RequestMapping("/monitor/redisMonitor")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class RedisMonitorController {

    private final RedisTemplate redisTemplate;

    @ApiOperation("获取服务信息")
    @SaCheckPermission("monitor:redisMonitor:get")
    @GetMapping("/getInfo")
    public Result getInfo() {
        // 获取redis缓存完整信息
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        // 获取redis缓存命令统计信息
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Map<String, Object> result = new HashMap<>(3);
        List<Map<String, String>> commandList = new ArrayList<>();
        result.put("info", info);
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            commandList.add(data);
        });
        result.put("commandList", commandList);
        return Result.ok("获取成功", result);
    }
}
